package com.zhanghu.backendZray.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhanghu.backendZray.cache.ContextCache;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    // 在插入记录时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createId", Integer.class, getCurrentUserId());
        this.strictInsertFill(metaObject, "updateId", Integer.class, getCurrentUserId());
    }

    // 在更新记录时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateId", Integer.class, getCurrentUserId());
    }

    // 获取当前用户的ID
    private Integer getCurrentUserId() {
        Integer currentUserId = ContextCache.currentUserId();
        return currentUserId == null ? 0 : currentUserId;
    }
}